package net.fredstar.polarbear;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

/**
 * TODO Comments.
 * 
 * @author Matthew Blackford [matthew@fredstar.net]
 */
public class SecureServer
{
  public static final int POLAR_BEAR_PORT = 52391;
  
  /**
   * Creates a new {@link SecureServer} instance.
   */
  public SecureServer()
  {

  }
  
  public void initialise() throws IOException, GeneralSecurityException
  {
    // Get the context factory
    SSLContextFactory contextFactory = SSLContextFactory.getInstance();
    
    // Create the context
    SSLContext context = contextFactory.createSecureContext(
        "test/keys/server.keystore", "123456", "test/keys/server.truststore",
        "123456" );
    
    // Create a server socket
    SSLServerSocketFactory serverSocketFactory = context
        .getServerSocketFactory();
    SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory
        .createServerSocket( POLAR_BEAR_PORT );
    
    // Require client authentication
    serverSocket.setNeedClientAuth( true );
    
    // Loop forever
    while ( true )
    {
      // Listen for an incoming connection
      System.out.println( "Listening on port: " + POLAR_BEAR_PORT );
      SSLSocket socket = (SSLSocket) serverSocket.accept();
      System.out.println( "Client connected" );
      
      // Create a socket handler
      SocketHandler handler = new SocketHandler( socket );
      handler.start();
    }
  }
  
  /**
   * TODO Comments.
   * 
   * @param args the command line arguments.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  public static void main( final String[] args ) throws IOException,
      GeneralSecurityException
  {
    new SecureServer().initialise();
  }
}
